<?php
/**
 * This class makes use of the Rewrite Engine written by Dean Newman
 *
 * Rewrite Engine
 *
 * This rewrite engine allowd for dynamic urls to be turn in to static urls
 * using the mod_rewrite apache extension, it functions by reading url schemas
 * created by its users in to an associative array of data.
 *
 * @author		Dean Newman < webmaster@auscoder.com >
 * @copyright	Copyright &copy; 2007, Dean Newman
 * @license		GNU/General Public License v2
 * @created		10:40AM 23/05/2007 GMT+10
 * @updated		10:40AM 23/05/2007 GMT+10
 */

if ( class_exists('rewrite_engine') )
{
///	return;
}

/**
 * Rewrite Engine Object
 * @version	1.0.0.0-php5
 */
class RewriteEngine
{
	public $raw;
	public $bits;
	public $path;
	public $url;

	public function __construct()
	{
		// Get the raw url bits
		$this->raw	= $_SERVER['REQUEST_URI'];
		
		// Parse the bits
		$this->bits	= explode('/', $_SERVER['REQUEST_URI']);
		
		for ( $i = 0 ; $i < sizeof($this->bits) ; $i++ )
		{			
			if ( $this->bits[$i] === '' )
			{
				unset($this->bits[$i]);
			}
		}
		
		ksort($this->bits);
		
		// Slice out directory path
		$this->bits = array_slice($this->bits, array_search(basename(dirname($_SERVER['SCRIPT_NAME'])), $this->bits), sizeof($this->bits) + 1);
		
		// Slice out filename
		$this->bits = array_slice($this->bits, array_search(basename($_SERVER['SCRIPT_NAME']), $this->bits) + 1, sizeof($this->bits) + 1);
		
		// Build the path object
		$this->path				= new RewriteEnginePath;
		$this->path->domain 	= $_SERVER['HTTP_HOST'];
		$this->path->path		= dirname($_SERVER['SCRIPT_NAME']);
		$this->path->port		= $_SERVER['SERVER_PORT'];
		$this->path->protocol	= isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
		$this->path->file		= basename($_SERVER['SCRIPT_NAME']);
		
		// Store the url as a string
		$this->url = (string) $this->path;
	}
	
	public function request($bit)
	{
		return isset($this->bits[$bit]) ? $this->bits[$bit] : false;
	}
	
	public function build($bits, $include_file = false)
	{
		$file = $include_file ? $file . '/' : '';
		$bits = is_array($bits) ? $bits : explode('/', $bits);
		return $this->url . $file . implode('/', $bits);
	}
	
	public function pop()
	{
		return array_pop($this->bits);
	}
	
	public function push($string)
	{
		$string = is_array($string) ? $string : explode('/', $string);
		return ($this->bits = $string + $this->bits) ? true : false;
	}
	
	public function shift()
	{
		return array_shift($this->bits);
	}
}

class RewriteEnginePath
{
	public $domain;
	public $path;
	public $port;
	public $protocol;
	public $file;
	
	public function __toString()
	{
		$port = ($this->port != 80 && $this->protocol == 'http') || ($this->port != 443 && $this->protocol == 'https') ? ':' . $this->port : '';
		return ($this->protocol . '://' . $this->domain . $port . $this->path . '/');
	}
}

?>